package com.xxh.basecrudframework.controller.common;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.*;
import java.lang.reflect.ParameterizedType;
import java.util.List;

@Slf4j
public class AbstractController<E, D, P> {

    public AbstractController() {
    }

    protected E paramToEntity(P param) {
        E entity = null;
        if (null != param) {
            try {
                entity = this.getEntityClass().newInstance();
                BeanUtils.copyProperties(param, entity);
            } catch (Exception var4) {
                log.error(var4.getMessage());
            }
        }

        return entity;
    }

    protected D entityToDto(E entity) {
        D dto = null;
        if (null != entity) {
            try {
                dto = this.getDtoClass().newInstance();
                BeanUtils.copyProperties(entity, dto);
            } catch (Exception var4) {
                log.error(var4.getMessage());
            }
        }

        return dto;
    }

    protected java.util.List<E> paramToEntity(java.util.List<P> paramList) {
        java.util.List<E> entityList = Lists.newLinkedList();
        if (null != paramList && paramList.size() > 0) {
            paramList.forEach((p) -> {
                E entity = this.paramToEntity(p);
                entityList.add(entity);
            });
        }

        return entityList;
    }

    protected List<D> entityToDto(List<E> entityList) {
        List<D> dtoList = Lists.newLinkedList();
        if (null != entityList && entityList.size() > 0) {
            entityList.forEach((e) -> {
                D dto = this.entityToDto(e);
                dtoList.add(dto);
            });
        }

        return dtoList;
    }

    private Class<E> getEntityClass() {
        java.lang.reflect.ParameterizedType parameterizedType = (java.lang.reflect.ParameterizedType)this.getClass().getGenericSuperclass();
        Type entityType = parameterizedType.getActualTypeArguments()[0];
        return (Class)entityType;
    }

    private Class<D> getDtoClass() {
        ParameterizedType parameterizedType = (ParameterizedType)this.getClass().getGenericSuperclass();
        Type dtoType = parameterizedType.getActualTypeArguments()[1];
        return (Class)dtoType;
    }
}
